package com.example.demo.dao;

import com.example.demo.domain.Stu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class CacheDemo {

  private JdbcTemplate jdbcTemplate;
  @Autowired(required = false)
  public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
    this.jdbcTemplate=jdbcTemplate;
  }

  @Cacheable(value = "allStus")
  public List<Stu> query() {
    List<Stu> stus = jdbcTemplate.query("select * from stu", (rs, row) -> {
      Stu stu = new Stu();
      stu.setId(rs.getLong("id"));
      stu.setUsername(rs.getString("username"));
      return stu;
    });
    log.info("--query db--");
    return stus;
  }

  @Cacheable(value="allStus", key="#id")
  public Stu findById(long id){
    return jdbcTemplate.queryForObject("select * from stu where id=1",(rs, row) -> {
      Stu stu = new Stu();
      stu.setId(rs.getLong("id"));
      stu.setUsername(rs.getString("username"));
      stu.setJava(rs.getDouble("java"));
      return stu;
    }) ;
  }
}